package org.itboys.core.controller.front;


import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.dto.ResultPageDOHelper;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.core.dto.advertisment.SundayAdvertisementDto;
import org.itboys.core.entity.mongo.SundayAdvertisement;
import org.itboys.core.util.ResponseMessage;
import org.itboys.core.service.mongo.front.SundayFrontAdvertisementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 作者：zzq
 * 日期：2018年9月4日
 * 描述：广告（新闻，轮播图）
 */
@Controller
@RequestMapping("/sunday/front/advertisement")
@Api(value = "advertisement", description = "广告")
public class SundayFrontAdvertisementController extends BaseController {
    @Autowired
    private SundayFrontAdvertisementService advertisementService;


    /**---------------------------广告信息--------------------------**/
    /**
     * 广告信息HTML5
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/html5", method = {RequestMethod.POST})
    public String html5(HttpServletRequest request,
                        Model model,
                        @RequestParam(value = "id", required = true) long id,
                        @RequestParam(value = "memberId", required = false) Long memberId) {
        SundayAdvertisement advertisement = advertisementService.getById(id);
        model.addAttribute("advertisement", advertisement);
        return "/sunday/advertisement/html5";
    }

    @RequestMapping(value = "/findOne", method = {RequestMethod.POST})
    public void findOne(HttpServletResponse response, HttpServletRequest request,
                        @RequestParam(value = "id", required = true) long id) {

        try {

            SundayAdvertisement advertisement = advertisementService.getById(id);
            ResponseMessage.success(advertisement);
        } catch (Exception e) {
            String msg = CommonConstants.ERROMSG;
            Integer code = CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if (e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")) {
                msg = e.getMessage();
                //token已过期
            } else if (e.getClass().getSimpleName().equalsIgnoreCase("TokenException")) {
                code = CommonConstants.TOKEN_CODE;
                msg = CommonConstants.TOKENMSG;
            } else {
                logger.error("/sunday/small/advertisement/findOne----e=" + e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code, msg);
        }

    }

    /**
     * @param response
     * @param request
     * @param zoneKey
     */

    @RequestMapping(value = "/getAdvertisementByZoneKey", method = {RequestMethod.POST})
    @ApiOperation(value = "根据广告位获取广告信息(列表信息)。不分页")
    public void getAdvertisementByZoneKey(HttpServletResponse response,
                                          HttpServletRequest request,
                                          @ApiParam(required = true, name = "zoneKey", value = "广告位key。" +
                                                  "1，index_roll（首页轮播图,）" +
                                                  "2，youxuan_roll（优选轮播图）" +
                                                  "3,about  (关于我们)") @RequestParam(value = "zoneKey", required = true) String zoneKey
    ) {
        try {
            List<SundayAdvertisementDto> advertisements = advertisementService.getAdvertisementByZone(zoneKey);
            AjaxUtils.renderJsonporJson(response, null,
                    ResultPageDOHelper.getMsgResultDO(advertisements, CommonConstants.SUCCESS));
        } catch (Exception e) {
            String msg = "";
            if (e.getClass().getSimpleName().equalsIgnoreCase("ErroException")) {
                msg = e.getMessage();
            } else {
                msg = CommonConstants.ERROMSG;
                logger.info("/sunday/small/advertisement/getAdvertisementByZoneKey--------" + e);
            }
            e.printStackTrace();
            AjaxUtils.renderJsonporJson(response, null,
                    ResultPageDOHelper.getMsgCodeResultDO(CommonConstants.FAIL_CODE, msg));
        }
    }

    /**
     * @param response
     * @param request
     * @param zoneKeys
     */

    @RequestMapping(value = "/getAdvertisementByZoneKeys", method = RequestMethod.POST)
    @ApiOperation(value = "批量多个广告位获取广告信息(列表信息)，可以传入多个广告位。不分页")
    public void getAdvertisementByZoneKeys(HttpServletResponse response,
                                           HttpServletRequest request,
                                           @ApiParam(required = true, name = "zoneKeys", value = "广告位key集合，列入：zoneKeys=1,2,3" +
                                                   "1，index_roll（首页轮播图,）" +
                                                   "2，index_news（首页滚动新闻）" +
                                                   "3，fanxian_roll（发现-轮播图）" +
                                                   "4，fanxian_cpmj（发现-菜谱秘籍）" +
                                                   "5，faxian_shcs（发现-生活常识）" +
                                                   "6，fanxian_xgjq（发现-选购技巧）") @RequestParam(value = "zoneKeys", required = true) List<String> zoneKeys
    ) {
        try {
            List<Map<String, Object>> results = advertisementService.getAdvertisementByZoneKeys(zoneKeys);
            AjaxUtils.renderJsonporJson(response, null,
                    ResultPageDOHelper.getMsgResultDO(results, CommonConstants.SUCCESS));
        } catch (Exception e) {
            String msg = "";
            if (e.getClass().getSimpleName().equalsIgnoreCase("ErroException")) {
                msg = e.getMessage();
            } else {
                msg = CommonConstants.ERROMSG;
                logger.info("/sunday/small/advertisement/getAdvertisementByZoneKey--------" + e);
            }
            e.printStackTrace();
            AjaxUtils.renderJsonporJson(response, null,
                    ResultPageDOHelper.getMsgCodeResultDO(CommonConstants.FAIL_CODE, msg));


        }
    }

    /**
     * 广告信息HTML5（直接根据广告位获取）
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/html5ByZoneCode", method = {RequestMethod.POST})
    @ApiOperation(value = "根据广告位获取网页（例如：用户协议等），返回的是网页内容，直接加载")
    public String html5ByZoneCode(HttpServletRequest request,
                                  Model model,
                                  @ApiParam(required = true, name = "zoneKey", value = "广告位key" +
                                          "1，member_protocol（用户协议,）" +
                                          "2，score_rule（积分、签到、兑换规则,）" +
                                          "3，income_rule（钱包充值（余额说明）,）" +
                                          "4，coupon_rule（优惠券规则,）" +
                                          "5,about_us(关于我们)" +
                                          "") @RequestParam(value = "zoneKey", required = true) String zoneKey
    ) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("zoneKey", zoneKey);
        param.put("isDeleted", 0);
        List<SundayAdvertisement> advertisements = advertisementService.list(param);
        if (ListUtil.isNotNull(advertisements)) {

            model.addAttribute("advertisement", advertisements.get(0));
        }

        return "/sunday/advertisement/html5";
    }
}
